<template>
  <div class="home">
    <ul v-for="(item, index) in goodsList">
      {{item.imgUrl}}
      {{item.price}}
      {{item.skuCount}}
      <el-button @click="handleToCart(item)">加入购物车</el-button>
      <hr>
    </ul>

    <el-button @click="handleRouterCart">跳转进入购物车页面</el-button>
  </div>
</template>

<script>
// @ is an alias to /src
// import HelloWorld from '@/components/HelloWorld.vue'
import { reactive, toRefs, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import ajax from '@/utils/request.js'
export default {
  // name: 'Home',
  // components: {
  //   HelloWorld
  // }
  setup(props) {
    // 1. 定义数据
    const state = reactive({
      goodsList: []
    })
    const router = useRouter()
    onMounted(() => {
      handleGetGoodsList({})
    })
    // 请求数据
    const handleGetGoodsList = async ({page = 0, size = 10}) => {
      const response = await ajax.get('/api/findGoods', {
        params: {
          page, size
        }
      })
      state.goodsList = response.data
    }

    // 加入购物车逻辑
    const handleToCart = async (item) => {
      // toCartItem
      const response = await ajax.get('/api/toCartItem', {params: {skuId: item.skuId }})
      // 封装一个toast调用
      // state.goodsList = response.data
    }

    // 跳转进入购物车页面逻辑
    const handleRouterCart = () => {
      router.push('/cart')
    }
    const { goodsList } = toRefs(state)
    return {
      goodsList,
      handleToCart,
      handleRouterCart
    }
  }
}
</script>
